package work.mediway.mdm.biz.service.biz.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mediway.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import com.mediway.bpm.enums.task.BpmProcessInstanceResultEnum;
import com.mediway.bpm.service.definition.BpmProcessDefinitionService;
import com.mediway.bpm.service.task.BpmProcessInstanceService;
import com.mediway.hos.app.base.seure.util.SecurityUtils;

import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ByteUtil;
import lombok.RequiredArgsConstructor;
import work.mediway.mdm.biz.entity.biz.BpmDict;
import work.mediway.mdm.biz.service.biz.BpmDictService;
import work.mediway.mdm.core.exception.DataException;
import work.mediway.mdm.biz.mapper.biz.BpmDictMapper;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2022/8/10
 */
@Service
@RequiredArgsConstructor
public class BpmDictServiceImpl extends ServiceImpl<BpmDictMapper, BpmDict> implements BpmDictService {

    private final BpmProcessInstanceService processInstanceService;
    private final BpmProcessDefinitionService processDefinitionService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long createDictApply(Long userId, BpmDict bpmDict) {
        bpmDict.setId(null);
        bpmDict.setCreator(SecurityUtils.getLoginName());
        bpmDict.setCreateTime(DateUtil.now());
        bpmDict.setResult(ByteUtil.intToByte(BpmProcessInstanceResultEnum.PROCESS.getResult()));
        this.save(bpmDict);

        ProcessDefinition definition = this.processDefinitionService.getProcessDefinition(bpmDict.getProcessDefinitionId());
        Map<String, Object> processInstanceVariables = MapUtil.newHashMap();
        processInstanceVariables.put("dict_data", bpmDict.getDictData());
        processInstanceVariables.put("table_code", bpmDict.getTableCode());
        String processInstanceId = this.processInstanceService.createProcessInstance(userId, (new BpmProcessInstanceCreateReqDTO())
                .setProcessDefinitionKey("dict_apply")
                .setVariables(processInstanceVariables)
                .setBusinessKey(String.valueOf(bpmDict.getId())));
        /*if (definition == null) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.PROCESS_DEFINITION_NOT_EXISTS);
        } else if (definition.isSuspended()) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.PROCESS_DEFINITION_IS_SUSPENDED);
        } else {
            ProcessInstance instance = this.runtimeService.startProcessInstanceById(definition.getId(), businessKey, variables);
            this.runtimeService.setProcessInstanceName(instance.getId(), definition.getName());
            this.processInstanceExtMapper.updateByProcessInstanceId((new BpmProcessInstanceExtDO()).setProcessInstanceId(instance.getId()).setFormVariables(variables));
            return instance.getId();
        }*/

        BpmDict dict = new BpmDict();
        dict.setId(bpmDict.getId());
        dict.setProcessInstanceId(processInstanceId);
        this.updateById(dict);
        return bpmDict.getId();
    }

    @Override
    public void updateDictApplyResult(long id, Integer result) {
        this.validateLeaveExists(id);
        BpmDict bpmDict = new BpmDict();
        bpmDict.setId(id);
        bpmDict.setResult(ByteUtil.intToByte(result));
        this.updateById(bpmDict);
    }

    private void validateLeaveExists(Long id) {
        if (this.getById(id) == null) {
            throw new DataException("申请不存在");
        }
    }
}
